<template>
  <div>
    <div class="title-top" @click="handeAdd">
      <i class="el-icon-edit"></i>
      <p>写点什么吧！</p>
    </div>
    <el-divider></el-divider>
    <div class="blog-item" v-for="blog in blogs" :key="blog.id">
      <el-card shadow="hover">
        <div class="title">
          <h3 @click="goBlogDetail(blog.id)">{{ blog.title }}</h3>
          <el-button type="primary" size="small" @click="handleEdit(blog.id)"
            >重新编辑</el-button
          >
        </div>
        <p class="desc">
          <span class="info">{{ blog.description }}</span>
        </p>
      </el-card>
    </div>
    <el-dialog title="博客" :visible.sync="dialogVisible" width="95%">
      <blog-editor
        @close-editor="closeEditor"
        :id="blogId"
        :dialog="dialogVisible"
      />
    </el-dialog>
  </div>
</template>

<script>
import userApi from "@/api/user";
import blogsApi from "@/api/blogs";
import BlogEditor from "./blogEditor/index";
export default {
  name: "userBlogs",
  components: {
    BlogEditor,
  },
  data() {
    return {
      blogId: null,
      dialogVisible: false,
      userId: null,
      userInfo: {},
      blogs: [],
    };
  },
  created() {
    this.userInfo = this.$store.getters.getUser;
    this.userId = this.userInfo.id;
    this.getBlogs();
  },
  methods: {
    closeEditor(flag) {
      this.dialogVisible = flag;
      this.getBlogs();
    },
    getBlogs() {
      userApi
        .getBlogsByUserId(this.userId)
        .then(({ data: res }) => {
          if (res.code === 200) {
            this.blogs = res.data.data;
          } else {
            return false;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handeAdd() {
      this.blogId = null;
      this.dialogVisible = true;
    },
    handleEdit(id) {
      this.blogId = id;
      this.dialogVisible = true;
    },
    goBlogDetail(id) {
      this.$router.push({
        path: "/blog",
        query: { id },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.blog-item {
  margin: 8px 0;
}
.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  h3 {
    cursor: pointer;
  }
}
.title-top {
  cursor: pointer;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  color: #409eff;
  p {
    margin-left: 10px;
  }
}
</style>